package cn.git;

import net.bytebuddy.agent.builder.AgentBuilder;
import net.bytebuddy.description.type.TypeDescription;
import net.bytebuddy.dynamic.DynamicType;
import net.bytebuddy.implementation.MethodDelegation;
import net.bytebuddy.implementation.SuperMethodCall;
import net.bytebuddy.matcher.ElementMatchers;
import net.bytebuddy.utility.JavaModule;

import java.security.ProtectionDomain;

public class ConstructorTransformer implements AgentBuilder.Transformer {

    /**
     * 构造方法进行插桩
     *
     * @param builder          The dynamic builder to transform.
     * @param typeDescription  The description of the type currently being instrumented.
     * @param classLoader      The class loader of the instrumented class. Might be {@code null} to represent the bootstrap class loader.
     * @param module           The class's module or {@code null} if the current VM does not support modules.
     * @param protectionDomain The protection domain of the transformed type.
     * @return A transformed version of the supplied {@code builder}.
     */
    @Override
    public DynamicType.Builder<?> transform(DynamicType.Builder<?> builder,
                                            TypeDescription typeDescription,
                                            ClassLoader classLoader,
                                            JavaModule module,
                                            ProtectionDomain protectionDomain) {

        System.out.println("ConstructorTransformer开始加载");

        return builder
                .constructor(ElementMatchers.any())
                .intercept(                        // 指定在构造方法执行完毕后再委托给拦截器
                        SuperMethodCall.INSTANCE.andThen(
                                MethodDelegation.to(new ConstructorInterceptor())
                        ));
    }
}
